package listener;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;

import model.GroupManager;
import model.Project;

import java.io.*;
import java.util.List;

@WebListener
public class ContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
    	ServletContext context = sce.getServletContext();

    	String studentFileParam = context.getInitParameter("studentFilePath");
    	String resultFileParam = context.getInitParameter("resultFilePath");
    	String projectFileParam = context.getInitParameter("projectFilePath");

    	System.out.println("studentFileParam: " + studentFileParam);
    	System.out.println("resultFileParam: " + resultFileParam);
    	System.out.println("projectFileParam: " + projectFileParam);

    	String studentFilePath = context.getRealPath(studentFileParam);
    	String resultFilePath = context.getRealPath(resultFileParam);
    	String projectFilePath = context.getRealPath(projectFileParam);

        // 获取分组参数
        String maxGroupSizeStr = context.getInitParameter("maxGroupSize");
        String totalGroupsStr = context.getInitParameter("totalGroups");

        // 将字符串转换为整数
        int maxGroupSize = Integer.parseInt(maxGroupSizeStr);
        int totalGroups = Integer.parseInt(totalGroupsStr);

        System.out.println("Student file path: " + studentFilePath);
        System.out.println("Result file path: " + resultFilePath);
        System.out.println("Project file path: " + projectFilePath);
        System.out.println("Max group size: " + maxGroupSize);
        System.out.println("Total groups: " + totalGroups);

        try {
            // 加载项目列表
            List<Project> projectList = Project.loadProjects(projectFilePath, totalGroups);
            context.setAttribute("projectList", projectList);

            GroupManager groupManager = new GroupManager(studentFilePath, resultFilePath, maxGroupSize, totalGroups);
            context.setAttribute("groupManager", groupManager);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void contextDestroyed(ServletContextEvent sce) {
        // 应用程序关闭时执行
    }
}
